<template>
  <div class="article-category-showcase">
    <div class="flex justify-between mb-2">
      <el-button type="primary" @click="openDialog">选择分类</el-button>
      <el-button v-if="modelValue.length > 0" @click="clearSelection">清空</el-button>
    </div>
    <div v-if="modelValue.length === 0" class="text-gray-400 text-center py-4">
      暂无选择分类
    </div>
    <el-table v-else :data="categoryList" :stripe="true" class="mb-4">
      <el-table-column label="分类名称" prop="name" min-width="200" show-overflow-tooltip />
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ $index }">
          <el-button
            type="primary"
            circle
            size="small"
            @click="removeCategory($index)"
          >
            <Icon icon="ep:delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分类选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择分类"
      width="60%"
      destroy-on-close
      append-to-body
    >
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="分类名称" prop="name">
          <el-cascader
            v-model="selectedCategoryIds"
            :options="categoryTree"
            :props="defaultProps"
            :show-all-levels="false"
            filterable
            clearable
            class="w-full"
            placeholder="请选择分类"
            multiple
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as ArticleCategoryApi from '@/api/mall/promotion/articleCategory'
import { handleTree } from '@/utils/tree'

// 扩展 ArticleCategoryVO 类型以支持树形结构
interface CategoryTreeNode extends ArticleCategoryApi.ArticleCategoryVO {
  children?: CategoryTreeNode[]
}

const props = defineProps<{
  modelValue: number[]
}>()

const emit = defineEmits(['update:modelValue'])

// 分类列表
const categoryList = ref<CategoryTreeNode[]>([])
// 分类树形数据
const categoryTree = ref<CategoryTreeNode[]>([])
// 弹窗是否显示
const dialogVisible = ref(false)
// 加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 选中的分类ID
const selectedCategoryIds = ref<number[] | undefined>(undefined)

// 级联选择器配置
const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  emitPath: false,
  multiple: true
}

// 查询参数
const queryParams = ref({
  pageNo: 1,
  pageSize: 100,
  name: ''
})

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await ArticleCategoryApi.getAllSimpleArticleCategoryList()
    categoryTree.value = handleTree(res, 'id', 'parentId')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 100,
    name: ''
  }
  handleQuery()
}

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  getList()
}

// 清空选择
const clearSelection = () => {
  emit('update:modelValue', [])
  categoryList.value = []
}

// 移除分类
const removeCategory = (index: number) => {
  const newValue = [...props.modelValue]
  newValue.splice(index, 1)
  emit('update:modelValue', newValue)
  categoryList.value.splice(index, 1)
}

// 确认选择
const handleConfirm = () => {
  if (selectedCategoryIds.value && selectedCategoryIds.value.length > 0) {
    emit('update:modelValue', selectedCategoryIds.value)
    // 更新显示的分类列表
    const findCategory = (tree: CategoryTreeNode[], id: number): CategoryTreeNode | undefined => {
      for (const node of tree) {
        if (node.id === id) return node
        if (node.children) {
          const found = findCategory(node.children, id)
          if (found) return found
        }
      }
      return undefined
    }
    const selectedCategories = selectedCategoryIds.value
      .map(id => findCategory(categoryTree.value, id))
      .filter((category): category is CategoryTreeNode => category !== undefined)
    categoryList.value = selectedCategories
  }
  dialogVisible.value = false
}

// 监听 modelValue 变化，更新分类列表
watch(
  () => props.modelValue,
  async (newIds) => {
    if (newIds.length > 0) {
      const categories = await Promise.all(
        newIds.map(id => ArticleCategoryApi.getArticleCategory(id))
      )
      categoryList.value = categories
    } else {
      categoryList.value = []
    }
  },
  {
    immediate: true
  }
)
</script>

<style scoped lang="scss">
.article-category-showcase {
  :deep(.el-table) {
    margin-top: 8px;
  }
}
</style> 